<template>
	<div class="system-role-container layout-padding">
		<div class="system-role-padding layout-padding-auto">
			<el-card shadow="hover" class="pageQueryBoxArea mb10">
				<el-form :model="state.param" :inline="true">
					<el-form-item label="订单来源：">
						<el-select v-model="state.param.source" placeholder="请选择订单来源" @change="sourceChange()">
							<el-option v-for="item in state.query.orderSource" :key="item.value"
								:label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="门店属性：">
						<el-select v-model="state.param.mode" placeholder="请选择门店属性" @change="modeChange()">
							<el-option v-for="item in state.query.storeType" :key="item.value"
								:label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="销售门店：">
						<el-select v-model="state.param.nodeId" placeholder="请选择门店" @change="search()">
							<el-option v-for="item in state.query.storeList" :key="item.id" :label="item.name"
								:value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="销售终端：">
						<el-select v-model="state.param.channel" placeholder="请选择销售终端" @change="search()">
							<el-option v-for="item in state.query.saleChannel" :key="item.value" :label="item.name"
								:value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="订单状态：">
						<el-select v-model="state.param.status" placeholder="请选择订单状态" @change="search()">
							<el-option v-for="item in state.query.orderStatus" :key="item.value"
								:label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="支付方式：">
						<el-select v-model="state.param.payType" placeholder="请选择支付方式" @change="search()">
							<el-option v-for="item in state.query.payType" :key="item.value" :label="item.label"
								:value="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="选择日期：">
						<el-date-picker v-model="state.param.dateTime" type="daterange" unlink-panels
							format="YYYY/MM/DD" value-format="YYYY-MM-DD" range-separator="-" :disabled-date="disabledDate"
							start-placeholder="开始日期" end-placeholder="结束日期" />
					</el-form-item>
					<el-form-item label="信息搜索：">
						<el-input v-model="state.param.keyword" placeholder="请输入关键字搜索" clearable></el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="search()">
							<el-icon>
								<ele-Search />
							</el-icon> 搜 索
						</el-button>
						<el-button type="primary" @click="search()">
							<el-icon>
								<ele-Refresh />
							</el-icon> 重 置
						</el-button>
					</el-form-item>
				</el-form>
			</el-card>
			<el-card shadow="hover" style="display: flex;flex-direction: column;flex: 1;height: inherit;">
				<section style="display: flex;flex-direction: column; flex: 1;height: inherit;">
					<el-tabs v-model="state.param.type" @tab-click="handleClick">
						<el-tab-pane v-for="item in state.query.orderType" :label="item.label" :name="item.value"  :key="item.value"></el-tab-pane>
					</el-tabs>
					<section class="orderAreaBox" >
						<el-row class="pl10 pr10" justify="center">
							<el-col class="flex-jCenter" style="" :span="6">商品/规格/属性/数量</el-col>
							<el-col class="flex-jCenter" :span="2">零售/实售单价</el-col>
							<el-col class="flex-jCenter" :span="2">零售/实售总价</el-col>
							<el-col class="flex-jCenter" :span="2">应付金额</el-col>
							<el-col class="flex-jCenter" :span="2">实付金额</el-col>
							<el-col class="flex-jCenter" :span="2">欠款金额</el-col>
							<el-col class="flex-jCenter" :span="2">订单状态</el-col>
							<el-col class="flex-jCenter" :span="2">会员/手机号</el-col>
							<el-col class="flex-jCenter" :span="2">销售员工/门店</el-col>
							<el-col class="flex-jCenter" :span="2">操作</el-col>
						</el-row>
						<section style="flex: 1;display: flex;flex-direction: column; flex: 1;height: inherit;" v-if="state.tableData.length > 0">
							<section v-for="(item, index) of state.tableData" :key="index" class="orderBox mt10" style="overflow-y: scroll;">
								<el-row class="orderItemTop pl10 pr10 pt5 pb5">
									<el-col :span="18" style="display:flex;align-items: center">
										<p>
											<span class="mr10">订单号：{{ item.snkey }}</span>
											<span class="mr10">销售时间：{{ item.alterTime }}</span>
											<span class="mr10">操作时间：{{ item.createdTime }}</span>
											<span class="mr10">订单来源：{{ item.source }}</span>
										</p>
									</el-col>
									<el-col :span="6" class="flex" style="justify-content:flex-end;">
										<el-button  v-if="item.status != '已撤销'" text type="primary"
											@click="onRevokeOrder(item.id, index)">撤销订单</el-button>
										<el-button  text type="primary" @click="addNote(item.snkey)">备注</el-button>
									</el-col>
								</el-row>
								<el-row class="goodsItem">
									<el-col :span="6">
										<div class="goodBox"  style="display: flex;justify-content: space-between;" v-for="(i) of item.itemsList" :key="i.id">
											<div style="display: flex;align-items: center;">
												<div style="width:64px; height: 64px;">
													<el-image style="width:64px; height: 64px;border-radius: 5px;" :src="i.cover" fit="cover" />
												</div>
												<div class="ml5">
													<p class="px2 goodMsg">{{ i.title }}</p>
													<p class="px2 goodMsg">{{ i.attrValues }}</p>
												</div>
											</div>
											<div class="mr15">
												x{{ i.number }}
											</div>
										</div>
									</el-col>
									<el-col :span="2">
										<div class="goodBox" style="justify-content: center;" v-for="(i) of item.itemsList"
											:key="i.id">
											<div>
												<del>￥{{ i.originPrice }}元</del>
												<p>￥{{ i.price }}元</p>
											</div>
										</div>
									</el-col>
									<el-col :span="2">
										<div class="goodBox" style="justify-content: center;" v-for="(i) of item.itemsList"
											:key="i.id">
											<div>
												<del>￥{{ i.originAmount }}元</del>
												<p>￥{{ i.amount }}元</p>
											</div>
										</div>
									</el-col>
									<el-col :span="2">
										<div>
											<p>￥{{ item.totalPay }}元</p>
										</div>
									</el-col>
									<el-col :span="2">
										<div>
											<p>￥{{ item.totalMoney }}元</p>
										</div>
									</el-col>
									<el-col :span="2">
										<div>
											<span>￥{{ item.arrears }}元</span>
										</div>
									</el-col>
									<el-col :span="2">
										<div>
											<span style="font-weight: bold;">{{ item.status }}</span>
											<section v-if="item.statusAddons != null">
												<span v-if="item.statusAddons.length > 0"><span v-for="(i, x) of item.statusAddons" :key="x" >{{ i }}</span></span>
											</section>
										</div>
									</el-col>
									<el-col :span="2">
										<div style="text-align: center"> {{ item.realName }}</div>
										<div style="text-align:center">
											{{ item.phone }}
										</div>
										
									</el-col>
									<el-col :span="2">
										<div style="text-align: center"> {{ rebateListFilters(item.itemsList) }}</div>
										<div style="text-align:center;padding: 5px 10px;">
											{{ item.node }}
										</div>
									</el-col>
									<el-col :span="2">
										<div>
											<el-button v-if="item.status == '待支付'"  text type="primary"
												@click="changePrice(item)">改价</el-button>
											<el-button v-if="item.status == '待发货'"  text type="primary"
												@click="deliverFun(item)">发货</el-button>
											<el-button  text type="primary"
												@click="onGoToDetailClick(item)">详情</el-button>
										</div>
									</el-col>
								</el-row>
								<template v-if="item.noteList?.length">
									<el-row class="orderItemBottom pl10 pr10 pt5 pb5"
										v-if="item.noteList && item.noteList.length >= 0">
										<el-col :span="18" style="display:flex;align-items: center">
											{{ item.noteList[0].note }}
										</el-col>
										<el-col :span="6" class="flex" style="justify-content:flex-end;">
											<el-button text type="primary">查看更多</el-button>
										</el-col>
									</el-row>
								</template>
							</section>
						</section>
						<section v-else>
							<el-empty :image-size="200" />
						</section>
					</section>
					<el-row justify="end">
						<el-col :span="24" class="flex-end-center">
							<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
								:pager-count="5" :page-sizes="[10, 20, 30]" v-model:current-page="state.param.pageNum" background
								v-model:page-size="state.param.pageSize" layout="total, sizes, prev, pager, next, jumper"
								:total="state.total">
							</el-pagination>
						</el-col>
					</el-row>
				</section>
			</el-card>
		</div>
		<changePriceDialog ref="changePriceDialogRef" @refresh="getOrderList()" />
		<deliverGoodDialog ref="deliverGoodDialogRef" @refresh="getOrderList()" />
	</div>
</template>

<script setup lang="ts" name="saleIndex">
import { reactive,onMounted,ref,defineAsyncComponent} from 'vue';
import { useRouter } from 'vue-router';
import type { saleOrderListData, storeNodeListData, channelListData } from "/@/types/order";
import { orderQuery, storeNodeList, channelList, orderAddNote, orderCancel } from '/@/api/order';
import { ElMessageBox, ElMessage, TabsPaneContext } from 'element-plus';
// 引入组件
const changePriceDialog = defineAsyncComponent(() => import('/@/views/order/sale/changePriceDialog.vue'));
const deliverGoodDialog = defineAsyncComponent(() => import('/@/views/order/sale/deliverGoodDialog.vue'));


const router = useRouter();
// 定义变量内容
const changePriceDialogRef = ref();
const deliverGoodDialogRef = ref();
const state = reactive({
	param: {
		source: null, // 0 门店 2 线上 //设置不了得值是哪个？
		mode: null, // 门店类型  null(默认) 全部 0 直营  1 加盟
		nodeId: null, // 门店id
		// 销售渠道
		channel: null,
		status: null,
		payType:null,
		dateTime: [],
		startTime: "",// 开始时间
		endTime: "",// 结束时间 
		timeInterval: 3, // 默认 null  时间范围  0 本月 1 本季度  2 今年  3 自定义时 须 startTime 和 endTime 时间可为null
		keyword: "",
		type: 999, 
		pageNum: 1,
		pageSize: 10,
	},
	query: {
		orderSource: [
			{ value: null, label: '全部' },
			{ value: 0, label: '门店订单' },
			{ value: 2, label: '线上订单' }
		],
		storeType: [
			{ value: null, label: '全部' },
			{ value: 0, label: '直营' },
			{ value: 1, label: '加盟' }
		],
		storeList: [] as Array<storeNodeListData>,
		saleChannel: [] as Array<channelListData>,
		orderStatus: [
			{ value: null, label: '全部' },
			{ value: 0, label: '待支付/到店付' },
			{ value: 1, label: '待发货' },
			{ value: 7, label: '待收货/待核销' },
			{ value: 8, label: '待评价' },
			{ value: 4, label: '已完成' },
			{ value: 11, label: '退款中' },
			{ value: 10, label: '已退款' },
			{ value: 6, label: '已关闭' },
			{ value: 14, label: '已撤销' },
		],
		payType: [
			{ value: null, label: '全部' },
		],
		orderType:[
			{ value: 999, label: '全部订单' },
		]
	},
	loading: false,
	total: 0,
	tableData: [] as Array<saleOrderListData>
});

onMounted(() => {
	// 获取订单列表
	getOrderList();
	// 获取门店列表
	getStoreNodeList();
	// 获取销售渠道列表
	getChannelList();
})

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

// 获取订单列表
const getOrderList = async () => {
	state.loading = true;//不用传参， 请求得入参在上面都定义了 param这里吗？
	// 对
	const { results } = await orderQuery(state.param);
	state.loading = false;
	state.tableData = results.records;
	state.total = results.total;
}

// 搜索
const search = () => {
	console.log(state.param)
	if (state.param.dateTime?.length == 2) {
		state.param.startTime = state.param.dateTime[0]
		state.param.endTime = state.param.dateTime[1]
	}
	state.param.pageNum = 1;
	getOrderList()
}


/**
 * 获取销售渠道列表
 */
 const getChannelList = async () => {
	const { results } = await channelList({ source: state.param.source, });
	state.query.saleChannel = results;
}

/**
 * 获取门店列表
 * mode  null /全部   0直营  1加盟
 */
const getStoreNodeList = async () => {
	const { results } = await storeNodeList({ mode: null, current: 1, size: 50 });
	let no1 = [{id:null,name:'全部'}]
	state.query.storeList = [...no1, ...results.records];
}

const handleClick = (tab: TabsPaneContext) => {
	let select = tab.props.name
	if (select != state.param.type) {
		state.param.pageNum = 1;
		state.param.type = select! as any;  //赋值 赋值是 + select!?  + 代表把字符串转为数字  ！ 是TS里面非空符号
		getOrderList();
	}
}


// 订单详情
const onGoToDetailClick = (item: any) => {
	console.log(item.id)
	router.push({
		path: '/order/sale/details',
		query: { id: item.id },
	});
};


// 分页点击 条数
const onHandleSizeChange = (val: number) => {
	state.param.pageSize = val;
	getOrderList();
};
// 分页点击
const onHandleCurrentChange = (val: number) => {
	state.param.pageNum = val;
	getOrderList();
};

// 添加备注
const addNote = (snkey: String) => {
	ElMessageBox.prompt(`商家备注`, '备注', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		inputPattern: /^.+$/,
		inputErrorMessage: '请输入备注',
	}).then(async ({ value }) => {
		let params = {
			snkey: snkey,
			note: value
		}
		let res = await orderAddNote(params);
		console.log(res)
		getOrderList();
		ElMessage.success('添加成功');
	}).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消',
		})
	})
}

// 撤销订单
const onRevokeOrder = (id: number, index: number) => {
	ElMessageBox.prompt(
		`您现在操作的是撤销订单，请慎重;该操作会使订单无效，同时用户消费数据、员工业绩、商品销量等相关数据均会撤销（恢复为之前的状态或数据）; 是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		inputPattern: /^.+$/,
		inputErrorMessage: '请输入订单撤销原因',
	}).then(async ({ value }) => {
		let params = {
			id: id,
			reason: value
		}
		let res = await orderCancel(params);
		console.log(res)
		state.tableData[index].status = '已撤销'
		ElMessage.success('撤销成功');
	}).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消',
		})
	})
};
 
// 订单改价
const changePrice = async ( item: any) => {
	changePriceDialogRef.value.openDialog(item);
}

// 订单发货
const deliverFun = (item: any) => {
	deliverGoodDialogRef.value.openDialog(item);
}

// 销售员工过滤器
const rebateListFilters = (item: any) => {
	let arr = item[0].rebateList
	if (Array.isArray(arr)) {
		let newArr = arr.map((obj: { id: any, employee: any, money: any; }) => obj.employee);
		let uniqueArr = [...new Set(newArr)];
		return uniqueArr.join('、')
	} else {
		return '--'
	}
}

// 来源切换
const sourceChange = async () => {
	state.param.mode = null;
	state.param.nodeId = null;
	state.param.channel = null;
	state.param.status = null;
	state.param.type = 999;
    getChannelList();
	if(state.param.source == null){
		state.query.orderStatus =  [
			{ value: null, label: '全部' },
			{ value: 0, label: '待支付/到店付' },
			{ value: 1, label: '待发货' },
			{ value: 7, label: '待收货/待核销' },
			{ value: 8, label: '待评价' },
			{ value: 4, label: '已完成' },
			{ value: 11, label: '退款中' },
			{ value: 10, label: '已退款' },
			{ value: 6, label: '已关闭' },
			{ value: 14, label: '已撤销' },
		];
		state.query.orderType = [
			{ value: 999, label: '全部订单' }
		];
	}else if(state.param.source == 0){
		state.query.orderStatus =  [
			{ value: null, label: '全部' },
			{ value: 1, label: '待支付' },
			{ value: 6, label: '退款中' },
			{ value: 7, label: '已退款' },
			{ value: 8, label: '已关闭' },
			{ value: 9, label: '已撤销' },
		];
		state.query.orderType = [
			{ value: 999, label: '全部订单' },
			{ value: 1, label: '销售订单' },
			{ value: 2, label: '充值订单' },
			{ value: 9, label: '储值卡订单' },
			{ value: 11, label: '活动订单' },
			{ value: 19, label: '付费会员订单' },
			{ value: 20, label: '换卡订单' },
			{ value: 7, label: '退款订单' },
		];
	}else if(state.param.source == 2){
		state.query.orderStatus =  [
			{ value: null, label: '全部' },
			{ value: 1, label: '待支付/到店付' },
			{ value: 2, label: '待发货' },
			{ value: 4, label: '待收货/待核销' },
			{ value: 4, label: '待评价' },
			{ value: 5, label: '已完成' },
			{ value: 6, label: '退款中' },
			{ value: 7, label: '已退款' },
			{ value: 8, label: '已关闭' },
		];
		state.query.orderType = [
			{ value: 999, label: '全部订单' },
			{ value: 23, label: '普通订单' },
			{ value: 25, label: '秒杀订单' },
			{ value: 26, label: '拼团订单' },
			{ value: 24, label: '砍价订单' },
			{ value: 28, label: '直播订单' },
			{ value: 27, label: '预定订单' },
			{ value: 29, label: '付费会员订单' },
		];
	}
	getOrderList();
}

// 门店类型切换 (如果不是全部则清空选中门店 以及订单选中状态)
const modeChange = () => {
	if(state.param.mode != null){
		state.param.nodeId = null
		state.param.status = null
	}
}
</script>
<style scoped lang="scss">
@import '../../../theme/mixins/index.scss';

:deep(.el-card__body){
	display: flex;
	flex-direction: column;
	flex: 1;
	height: inherit;
	.orderAreaBox{
		display: flex;
		flex-direction: column;
		flex: 1;
		height: inherit;
		.orderBox{
			flex: 1;
		}
	}
}


.orderBox {
	border: 1px solid var(--el-card-border-color);
	.orderItemTop {
		background: var(--next-bg-color);
		border-bottom: 1px solid var(--el-card-border-color);
		p {
			@include text-no-wrap;
		}
	}

	.goodsItem {
		.goodBox {
			display: flex;
			justify-content: flex-start;
			align-items: center;
			padding: 2px 5px;
			border-bottom: 1px solid var(--el-card-border-color);
			box-sizing: border-box;
			height: 76px;
			width: 100%;
			overflow: hidden;
			.goodMsg {
				@include text-ellipsis(2);
			}
			p {
				@include text-ellipsis(1);
			}
		}

		.goodBox:last-child {
			border-bottom: none;
		}

		.el-col {
			display: flex;
			align-items: start;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			border-right: 1px solid var(--el-card-border-color);
			min-height: 74px;
		}

		.el-col:last-child {
			border-right: none;
		}
	}

	.orderItemBottom {
		background: var(--next-bg-color);
		color: var(--el-table-text-color);
		border-top: 1px solid var(--el-card-border-color);

	}
}</style>
